<?php @session_start();?>
<?php
require_once('./safe.php');
require_once('../admin/config.php');
function http_get($url){
$headers[] = "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36";
//$headers[] = "Zoomkey-Auth-Token: 9CD0F0F60AFDF00";
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$tmpInfo = curl_exec($curl);
curl_close($curl);
return $tmpInfo;
}
function trimd($str){
 return str_replace("'","''",$str);
}

$conn = mysql_connect($cfg_dbhost,$cfg_dbuser,$cfg_dbpwd);
mysql_select_db($cfg_dbname,$conn);
$sql="select * from ph_user where user_name='".$_SESSION["username"]."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$sqltdk="select * from ph_tdk where 1=1";
$resulttdk=mysql_query($sqltdk);
$rowtdk=mysql_fetch_array($resulttdk);

$url=$_REQUEST["package"];
$thetype=$_REQUEST["thetype"];

if(!empty($url)){
    if($thetype=="apple"){
        if(strpos($url,'http')===false){ 
            $url='https://apps.apple.com/dk/app/company/'.$url;
        }
        $content = http_get($url."?time=".time());

        if(!empty($content)){
            $img=explode("srcset=\"",$content);
            $icon=explode("1x,",$img[1]);
            $app=explode("title\" content=\"",$content);
            $app_name=explode("\" class=",$app[1]);
        }else{
            header('Content-type:text/json');
            echo "{\"status\":false,\"errors\":[\"Didn't find a match on the package name, or could not fetch the App information\"]}";
            exit;
        }
    }else{
        if(strpos($url,'http')===false){ 
            $url='https://play.google.com/store/apps/details?id='.$url;
        }
        $content = http_get($url."&time=".time());

        if(!empty($content)){
            $img=explode("class=\"xSyT2c\"><img src=\"",$content);
            $icon=explode("\" srcset=\"",$img[1]);
            $app=explode("og:title\" content=\"",$content);
            $app_name=explode(" - Apps on Google",$app[1]);
            
        }else{
            header('Content-type:text/json');
            echo "{\"status\":false,\"errors\":[\"Didn't find a match on the package name, or could not fetch the App information\"]}";
            exit;
        }
    }
// ECHO $app_name[0].$icon[0];
// EXIT;
    $apn=trimd($app_name[0]);
    $url=trimd($url);
    $imgu=trimd($icon[0]);
$sqla="select * from ph_myapp where userid='".$_SESSION["userid"]."' and app_name='".$apn."'";
$resulta=mysql_query($sqla);
if(mysql_num_rows($resulta)>=1){
    header('Content-type:text/json');
    echo "{\"status\":false,\"errors\":[\"You've already added this app\"]}";
    exit;
}else{
$sqlb = "INSERT INTO ph_myapp(app_name,url,cdate,icon,userid,thetype)VALUES('".$apn."','".$url."','".date('Y-m-d H:i:s',time())."','".$imgu."','".$_SESSION["userid"]."','".$thetype."')";
mysql_query($sqlb,$conn);
header("Content-type:application/json");
echo "{\"status\":true,\"errors\":[\"0\"]}";
exit;
}

}

function imgtobase64($img='', $imgHtmlCode=true)
{
$imageInfo = getimagesize($img);
$base64 = "" . chunk_split(base64_encode(file_get_contents($img)));
return 'data:' . $imageInfo['mime'] . ';base64,' . chunk_split(base64_encode(file_get_contents($img)));
}


?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

                    <link rel="apple-touch-icon" sizes="180x180" href="/images/iosinstalls/favicon/apple-touch-icon.png">

            <meta name="theme-color" content="#ffffff">

        <title><?php echo $rowtdk["sitename"];?> - Dashboard</title>

        <link href="../css/customer-iosinstalls.css?id=a9a9c5930bcdb195e9ee" rel="stylesheet">
        <link rel="stylesheet" type="text/css" href="<?php if(!empty($rowtdk["fontlink"])){echo '//fonts.googleapis.com/css?family='.$rowtdk["fontlink"];}else{echo "//fonts.googleapis.com/css?family=Roboto:300,400,500";}?>">
        <style type="text/css">
            body{font-family: '<?php echo $rowtdk["fontlink"];?>';}
        </style>        
    </head>

    <body class="app header-fixed sidebar-fixed aside-menu-fixed aside-menu-hidden">
    <?php include("head.php");?> 
    <?php include("left.php");?>

            <!-- Main content -->
            <main class="main">
                    <div class="container-fluid padding-top">
        
        <div class="row">
            <div class="col-lg-6">
                <div class="card">
                    <div class="card-header bg-primary">
                        <i class="fa fa-plus"></i> <b>Add App</b>
                    </div>
                    <div class="card-body">
                        <div id="errors" class="alert alert-danger hidden"></div>
                        <form id="addApp">
                            <fieldset class="form-group">
                                  <label>Please Select The APP Store</label>
                                <div class="input-group">
                                    <select id="thetype" name="thetype" class="form-control">
  <option value ="apple">Apple Store</option>
  <option value ="google">Goole Play Store</option>
</select>

                                </div>
                                
                                <label>Package Name/ID or Full URL</label>
                                <div class="input-group">
                                    <span class="input-group-prepend">
                                        <span class="input-group-text">
                                            <i class="fa fa-mobile-android-alt"></i>
                                        </span>
                                    </span>
                                    <input type="text" class="form-control" id="package" name="package" autocomplete="off" />
                                </div>
                                <small class="text-muted">Examples:</small>
                                <small><b>Apple App Store</b></small>
                                <small class="text-muted">https://apps.apple.com/dk/app/company/id284882215</small>
                                <small class="text-muted">id284882215</small>
                                <small><b>Goole Play Store</b></small>
                                <small class="text-muted">https://play.google.com/store/apps/details?id=com.betterme.argame</small>
                                <small class="text-muted">com.betterme.argame</small>
                            </fieldset>


                            <button class="btn btn-primary ladda-button" type="submit" id="add">Add</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header bg-primary">
                        <i class="fa fa-edit"></i> <b>Apps</b>
                    </div>
                    <div class="card-body">
                        <div id="update-messages" class="alert alert-danger hidden"></div>
                        <div class="table-responsive">
                            <table class="table table-hover mb-0">
                                <thead class="thead-default">
                                <tr>
                                                                        <th width="50px">Icon</th>
                                    <th>Name</th>
                                    <th>Type</th>
                                    <th></th>
                                </tr>
<?php 
$sqla="select * from ph_myapp where userid='".$_SESSION["userid"]."'";
$resulta=mysql_query($sqla);
while($rowa=mysql_fetch_array($resulta)){?>
                                <tr>
                                                                        <td width="50px"><img src="<?php echo $rowa["icon"];?>" width="50" /></td>
                                    <td><?php echo $rowa["app_name"];?></td>
                                    <td><?php if($rowa["thetype"]=="apple"){echo "<img src='../images/stores/apple_black.png'>";}else{echo "<img src='../images/stores/android_black.png'>";}?></td>
                                    <td><i class="fa fa-redo cursor-pointer update-app" data-app-id="<?php echo $rowa["ID"];?>"></i><button class="btn btn-danger delete-app ml-3" title="Delete" data-app-id="<?php echo $rowa["ID"];?>"><i class="fa fa-times"></i></button></td>
                                </tr>
<?php }?>
                                </thead>
                                <tbody>
                                                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

            </main>
        </div>

        <footer class="app-footer">
                            &copy; 2021 <?php echo $rowtdk["sitename"];?>. All Rights Reserved
                        <div class="pull-right">
                Server time: <?php echo date('d-m-Y H:i:s',time());?>
            </div>
        </footer>

        <!-- Bootstrap and necessary plugins -->
        <script src="/js/backend.js?id=27298b157affa1f728a9"></script>

        
        <script type="text/javascript">
        $(function() {
            var submitLadda = Ladda.create(document.querySelector('.ladda-button'));

            $.validator.setDefaults({
                submitHandler: function () {
                    submitLadda.start();

                    $.ajax({
                        url: "",
                        type: "POST",
                        data: {
                            "package": $('#package').val(),
                            "thetype": $('#thetype').val()
                        },
                        success: function (response) {
                            submitLadda.stop();

                            if (response.status) {
                                //alert(response.message);
                                if (response.message) {
                                    $('#errors').removeClass('hidden alert-danger').addClass('alert-warning');
                                    $('#errors').html(response.message);
                                } else {
                                    location.reload();
                                }
                            } else {
                                $('#errors').removeClass('hidden');
                                $('#errors').text(response.errors[0]);
                            }
                        },
                        error: function() {
                            submitLadda.stop();
                        }
                    });
                }
            });

            $('#addApp').validate( {
                rules: {
                    "package": 'required'
                },
                messages: {
                    "package": 'Please enter the apps package name'
                },
                errorElement: 'div',
                errorPlacement: function ( error, element ) {
                    // Add the `help-block` class to the error element
                    error.addClass( 'form-control-feedback' );
                    error.insertAfter( $(element).parent() );
                },
                highlight: function ( element, errorClass, validClass ) {
                    $( element ).addClass( 'form-control-danger' ).removeClass( 'form-control-success' );
                    $( element ).parents( '.form-group' ).addClass( 'has-danger' ).removeClass( 'has-success' );
                },
                unhighlight: function (element, errorClass, validClass) {
                    $( element ).addClass( 'form-control-success' ).removeClass( 'form-control-danger' );
                    $( element ).parents( '.form-group' ).addClass( 'has-success' ).removeClass( 'has-danger' );
                }
            });

            $('.update-app').click(function() {
                var icon = $(this);
                if (!icon.hasClass('fa-spin')) {
                    $('#update-messages').addClass('hidden');
                    icon.addClass('fa-spin');

                    $.ajax({
                        url: '/dashboard/update-app.php',
                        type: 'POST',
                        data: {
                            app_id: $(this).data('app-id'),
                        },
                        success: response => {
                            icon.removeClass('fa-spin');
                            if (response.status) {
                                window.location.reload();
                            } else {
                                $('#update-messages').removeClass('hidden').text('Something went wrong');
                            }
                        },
                        error: errors => {
                            icon.removeClass('fa-spin');
                            $('#update-messages').removeClass('hidden').text('Something went wrong')
                        }
                    })
                }
            });

            $('.delete-app').click(function() {
                if (confirm('Are you sure you want to delete this app?')) {
                    $('#update-messages').addClass('hidden');

                    $.ajax({
                        url: '/dashboard/delete-app.php',
                        type: 'POST',
                        data: {
                            app_id: $(this).data('app-id'),
                        },
                        success: response => {
                            if (response.status) {
                                window.location.reload();
                            } else {
                                $('#update-messages').removeClass('hidden').text('Something went wrong');
                            }
                        },
                        error: errors => {
                            $('#update-messages').removeClass('hidden').text('Something went wrong')
                        }
                    })
                }
            });
        });
    </script>

       
                        </body>
</html>